//
//  ImageHash.m
//  TestDemo
//
//  Created by fengxijun on 16/6/8.
//  Copyright © 2016年 goappbox. All rights reserved.
//

#import "ImageHash.h"

@implementation ImageHash

+ (NSInteger)hammingDistance:(NSString *)sourceHashCode hashCode:(NSString *)hashCode {
    NSInteger difference = 0;
    NSInteger len = [sourceHashCode length];
    
    for (NSInteger i = 0; i < len; i++) {
        if ([sourceHashCode characterAtIndex:i] != [hashCode characterAtIndex:i]) {
            difference ++;
        }
    }
    
    return difference;
}

+ (UInt32) grayWithR:(int)r g:(int)g b:(int)b
{
    return (UInt32) (0.3 * r + 0.59 * g + 0.11 * b);
//    float gray = 0.299*r + 0.587*g + 0.114*b;
//    return gray;
}

+ (UInt32) rgbToGray:(UInt32)pixels {
    // int _alpha = (pixels >> 24) & 0xFF;
    int _red = (pixels >> 16) & 0xFF;
    int _green = (pixels >> 8) & 0xFF;
    int _blue = (pixels) & 0xFF;
    return (int) (0.3 * _red + 0.59 * _green + 0.11 * _blue);
}

+ (UInt32) average:(UInt32*)pixels count:(size_t)count {
    float m = 0;
    for (size_t i = 0; i < count; i += 4) {
        m += pixels[i];
    }
    m = m / count;
    return (UInt32) m;
}

+ (char) binaryToHex:(UInt32)binary {
    char ch = ' ';
    switch (binary)
    {
        case 0:
            ch = '0';
            break;
        case 1:
            ch = '1';
            break;
        case 2:
            ch = '2';
            break;
        case 3:
            ch = '3';
            break;
        case 4:
            ch = '4';
            break;
        case 5:
            ch = '5';
            break;
        case 6:
            ch = '6';
            break;
        case 7:
            ch = '7';
            break;
        case 8:
            ch = '8';
            break;
        case 9:
            ch = '9';
            break;
        case 10:
            ch = 'a';
            break;
        case 11:
            ch = 'b';
            break;
        case 12:
            ch = 'c';
            break;
        case 13:
            ch = 'd';
            break;
        case 14:
            ch = 'e';
            break;
        case 15:
            ch = 'f';
            break;
        default:
            ch = ' ';
    }
    return ch;
}

+ (PHAHammingDistanceType)checkImagePHA:(NSString *)source destion:(NSString *)destion {
    NSInteger difference = [self hammingDistance:source hashCode:destion];
    if (difference == 0) {
        return PHAHammingDistanceWithSame;
    }
    if (difference <= 5) {
        return PHAHammingDistanceWithMore;
    }
    
    if (difference <= 10) {
        return PHAHammingDistanceWithLittle;
    }
    
    return PHAHammingDistanceWithDifferent;
}

@end
